/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */
const { app, BrowserWindow, ipcMain, dialog } = require('electron');

// if (require('electron-squirrel-startup')) return app.quit();

app.commandLine.appendSwitch("--disable-http-cache");
app.commandLine.appendSwitch('trace-warnings')
process.traceProcessWarnings = true;
const path = require('path');
const getPort = require('get-port');
const server = require('./server');
const discover = require('./discover');
let serverPort = -1;
console.log(app.getAppPath());
let MAIN_WINDOW_NAME_PROFIX = "UBlockly IDE ";
let mainWindow;
function createWindow() {
    if (serverPort <= 0) {
        throw Error('Server has not started.');
    }
    mainWindow = new BrowserWindow({
        width: 1180,
        height: 800,
        webPreferences: {
            preload: path.join(app.getAppPath(), '/static/editor/js/preload.js'),
            devTools: true,
        },
        title: MAIN_WINDOW_NAME_PROFIX
    });
    // mainWindow.webContents.openDevTools();
    setTimeout(() => {
        let url = `http://localhost:${serverPort}/index.html`;
        console.log(url);
        mainWindow.loadURL(url);
        mainWindow.title = MAIN_WINDOW_NAME_PROFIX;
    }, 1000);
}


app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});
app.whenReady().then(() => {
    getPort().then((p) => {
        serverPort = p;
        server.start(p, () => {
            discover.start(p);
            createWindow();
        });
    });
});

app.on('window-all-closed', () => {
    // if (process.platform !== 'darwin') {
    app.quit();
    // }
});
// ipcMain.on('setProjectInfo', (event, info) => {
//     let path = info.path;
//     let name = info.name;
//     discover.setMessage(name);
//     server.setProjectPath(path)
// });
ipcMain.handle('dialog', async (event, methdoName, ...args) => {
    const result = dialog[methdoName](mainWindow, ...args);
    return result
});
let serverCmdHandler = {
    setProjectInfo(info) {
        if (info) {
            let name = info.name;
            let min = 1000;
            let max = 9999;
            let r = Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值 
            let title = r + "-" + name;
            discover.setMessage(title);
            mainWindow.title = title + "-" + MAIN_WINDOW_NAME_PROFIX;;
        } else {
            mainWindow.title = MAIN_WINDOW_NAME_PROFIX;;
        }
        server.setProjectPath(info)
    }
};
ipcMain.handle('server', (evt, methodName, ...args) => {
    return serverCmdHandler[methodName](...args);
});
ipcMain.on("appPath", (evt) => {
    evt.returnValue = app.getAppPath();
});